<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/27 0027
 * Time: 22:09
 */

namespace App\Listener;

use Firebase\JWT\JWT;
use Lib\Core\ConfigLoad;
use Lib\Core\WebSocket\WebSocketContext;

/**
 * @Listener(ws.message)
 * @description:
 * @auth:yfl
 * @email:554665488@qq.com
 * Class OpenListener
 * @package App\Listener
 */
class MessageListener
{
    public function handel($params)
    {
//        var_dump("Message事件触发");
        $frame = $params['frame'];
        $redis = $params['redis'];
        $server = $params['server'];
        $data = json_decode($frame->data, true);
        switch ($data['method']) {
            case 'server_broadcast':
                //给不再本机上的客户端通过路由服务器广播消息
                $request = WebSocketContext::getRequest($frame->fd);
                $token = $request->header['sec-websocket-protocol'];
                $config = ConfigLoad::getInstance();
                $config->load();//载入配置文件
                $key = $config::get('JwT_key');
                $parseToken = JWT::decode($token, $key, ['HS256']);
                $userInfo = $parseToken->data;
                $services = $redis->SMEMBERS('im_service');
                //排除本机服务
                $service_url = $userInfo->service_url;
//                var_dump('当前的服务',$service_url);
//                var_dump('存在的服务',$services);
                //给不在本机上的客户端,通过路由服务器广播消息(排除当前的机器)
                foreach ($services as $index => $service) {
                    $service = json_decode($service, true);
                    if ($service['ip'] . ':' . $service['port'] == $service_url) {
//                        unset($services[$index]);
                    }
                }
//                var_dump('过滤后的服务',$services);
                //转发给服务中心
                $cli = new \Swoole\Coroutine\http\Client("106.14.120.16", 9504);
                $ret = $cli->upgrade("/"); //升级的websockt
                if ($ret) {
                    $route_data = ['method' => 'route_broadcast', 'target_server' => $services, 'msg' => $data['msg']];
                    $cli->push(json_encode($route_data));
                }
                //如果当前的服务端连接了客户端就直接发
                $this->sendAll($server, $data['msg']);
                break;
            case 'route_broadcast': ////接收到服务器广播
                $this->sendAll($server, $data['msg']);
                break;
        }

    }

    public function sendAll($server, $msg)
    {
        foreach ($server->connections as $fd) {
            if ($server->exist($fd)) {
                $server->push($fd, $msg);
            }
        }
    }
}